/**
 * by lcs
 */
(function(win,$ ){
	var LINES = 2; //line ：    多少行物品
	var LINE_HEIGHT = 100; // px 一行物品的高度
	var SPEED_PX = 2; //px      物品一次移动的距离
	var SPEED_TIME = 30; //ms   移动一次物品的时间间隔
	var NEW_GOODS_TIME = 1000; //s 产生新的时间间隔
	var TOTAL_TIME = 30; //s    游戏的总时间
	var MAX_WIDTH = 500;//px    物品移动的最大宽度，超出这个范围会删掉
	var GOODS_OFFSET = 35; //px 抓取物品时的一个错位纠正
	var ROB_RANGE = 40; //px    抓取该范围内的物品
	var H_RAND = 200 ; //px     物品水平方向的散乱程度
	var V_RAND = 50 ;  //px     物品垂直方向的散乱程度
	var STSRT_COUNTDOWN = 3;//s 游戏开始倒计时

	var containerSelector = "#main-box";
	var GOODS = {
		g1:{
			css:'g1', 	//css样式 
			score:-1, 	//分数，可用于区分炸弹
			r:2 		//出现概率（计算方法  r1 / ( r1 + r2 + r3 + rn ) ）
		},
		g2:{
			css:'g2',
			score:-2,
			r:1
		},
		g3:{
			css:'g3',
			score:-3,
			r:1
		},
		g4:{
			css:'g4',
			score:2,
			r:1
		},
		g5:{
			css:'g5',
			score:1,
			r:12
		},
		g6:{
			css:'g6',
			score:1,
			r:14
		},
		g7:{
			css:'g7',
			score:1,
			r:12
		},
		g8:{
			css:'g8',
			score:1,
			r:12
		}

	};

	var Helper = {
		container:$(containerSelector),
		rand:function(min,max){
			if(!max){
				max = min ;
				min = 0;
			}

			var rang = max - min;
			return min + Math.floor( Math.random() * rang );
		},

		randomGoods:(function(){
			var total = 0;
			var map = {};
			var defaultKey ;
			$.each(GOODS, function(k, goods) {
				var max = total + goods.r;
				map[k] = {
					key:k,
					min : total ,
					max : max 
				};
				defaultKey = k;
				total = max;
			});

			return function(){
				var num = Helper.rand(total);
				var goods = false;
				$.each(map,function(k , tmp){
					if( num >= tmp.min && num < tmp.max ){
						goods = GOODS[tmp.key];
						return false;
					}
				});
				return goods || GOODS[defaultKey];
			}
		})(),
		distance:function(p1,p2){
			var a = p1.left - p2.left;
			var b = p1.top - p2.top;
			return Math.pow( Math.pow(a,2) + Math.pow(b,2) , 0.5 ); 
		},
		countScore:function(goods){
			var s = 0;
			goods.forEach(function(g){
				if( g.type.score == 1 ){
					s++;
				}else{
					s *=  g.type.score ;
					// s *=  parseInt((Math.random()*97).toFixed(0))+2;
				}
			});
			return s;
		}
	};

	var Goods = function( type ){
		this.top = 0;
		this.left = -50;
		this.type =  type;
		this.giftTimes = Helper.rand(2,10);

		this.$html = $("<div id=good ></div>").addClass(type.css).css("left",this.left).css("top",this.top);
		this.type.score > 1 && this.$html.append('<span class=giftTimes >' +"X" + this.giftTimes + '</span>')
		
		Helper.container.append(this.$html);
	};

	Goods.prototype.move = function(){
		this.left += SPEED_PX;
		this.$html.css("left",this.left).css("top",this.top);
	}

	Goods.prototype.update = function(pos){
		this.left = pos.left;
		this.top = pos.top;
		this.$html.css("left",this.left + Helper.rand(3)).css("top",this.top + Helper.rand(3));
	};


	var Game = function(){
		this.goods = [];
		this.robGoods = [];
		this.moveTimeId = 0;
		this.newGoodsTimeId = 0;
		this.countTimeId = 0;
		this.isRuning = false;
		this.totalScore = 0;

		this.times = TOTAL_TIME;

		var $this = this;
		var listeners = {};

		this.trigger = function(type,args){
			$.each(listeners[type]||{},function(i,fun){
				fun.call($this,args);
				console.log(type,i)
				
			});
		};

		this.on = function(type , fun ){ 
			listeners[type] = listeners[type] || [];
			listeners[type].push(fun);
			return this;
		};

		["start","end","rob","countDown"].forEach(function(name){
			$this["on"+ name.substr(0,1).toLocaleUpperCase() + name.substr(1) ] = function(fun){
				$this.on(name,fun);
				return $this;
			}
		});

	};


	Game.prototype.start = function(){
		this.robGoods = [];
		this.goods = [];
		this.times = TOTAL_TIME;
		this.resume();
		

		this.trigger('start');

	};

	Game.prototype.pause = function(){
		this.moveTimeId && clearInterval(this.moveTimeId);
		this.newGoodsTimeId && clearInterval(this.newGoodsTimeId);
		this.countTimeId && clearInterval(this.countTimeId);
		this.isRuning = false;
		this.isEnd = false;
	};

	Game.prototype.resume = function(){
		if(this.isEnd)return;
		this.pause();
		this.isRuning = true;
		var $this = this;

		this.newGoods();

		var removeGoods = function(goods){
			var  tmp ;

			for( var i = 0 ; i < goods.length  ; i++ ){
				if(!goods[i] || goods[i].left > MAX_WIDTH ){
					tmp = goods[i];
					goods[i] = goods[goods.length - 1 ];
					goods[goods.length - 1 ] = tmp;
					goods.pop();
					tmp && tmp.$html && tmp.$html.remove();
				}
			}
		};


		this.moveTimeId = setInterval((function(goods){
			return function(){
				removeGoods(goods);
				goods.forEach(function(g){
					if(!g){
						console.log(goods);
					}
					g && g.move();
				});
			}
		})(this.goods),SPEED_TIME);

		this.countTimeId = setInterval(function(){
			$this.times--;
			$this.trigger("countDown",$this.times);
			if( $this.times <= 0 ){
				$this.stop();
			}
		},1000);
	}

	Game.prototype.stop = function(){
		this.pause();
		this.isEnd = true;

		this.trigger('stop');
		this.trigger('end');
	};

	Game.prototype.newGoods = function(){
		this.newGoodsTimeId = setInterval((function( goods ){
			var f =  function(){
				var g;
				for( var i = 0 ; i < LINES ; i++ ){
					g = new Goods(Helper.randomGoods());
					g.top = LINE_HEIGHT * i + Helper.rand(5,V_RAND);
					g.left = Helper.rand(-1 * H_RAND - 100,-100);

					goods.push(g);
				}
			};
			f();
			return f;
		})( this.goods ) , NEW_GOODS_TIME );		
	};

	Game.prototype.rob = function( pos ){
		var c = [] , g ;
		for( var i = 0 ; i < this.goods.length ; i++ ){
			g = this.goods[i];
			if(!g)continue;

			if( Helper.distance(g,pos) > ROB_RANGE )continue;

			this.goods[i] = this.goods[this.goods.length-1];
			this.goods.pop();
			c.push(g);
			this.robGoods.push(g);
			i--;
			if( g.type.score > 0 ){
				if( g.type.score > 1 ){
					this.totalScore *= g.giftTimes;
				}else{
					this.totalScore += g.type.score;
				}
			}
			this.trigger('rob',g);
		}

		return c;
	};
/************************************************************************/
	//new Game().start();

	var test = function(pos){
		pos.left = pos.left || pos.x;
		pos.top = pos.top || pos.y;

		Helper.container.append($("<div class=test-point ></div>").css(pos));
	};


	var countToStart = function( t ){
		if( t == 0 ){
			init();
		}else{
			$(".overlayer, .overlayer .countdown").removeClass("fn-hide").find(".text").html(t);
			setTimeout(function(){
				countToStart(t-1);
			},1000);
		}
	};

	var init = function(){
		var $hand = Helper.container.find(".hand").removeClass("fn-hide");
		var o = {left:Helper.container.width()*0.5};
		var lock = false;
		var game = new Game();

		$hand.css("left",(Helper.container.width()-$hand.width())*0.5);
		o.top =  Helper.container.height() - $hand.css("bottom").replace(/px/,'')*1||0;

		var getPos = function(e){
			var pos = {};

			pos.left = e.offsetX;
			pos.top = e.offsetY;

			if(e.target.id.match(/good/ig)){
				pos.left += $(e.target).css("left").replace(/px/,'')*1 || 0
				pos.top += $(e.target).css("top").replace(/px/,'')*1 || 0
			}else if( !e.target.id.match(/main/) ){
				return false;
			}

			return pos;
		};

		var updateRobGoods = function( goods , pos ){
			goods.forEach(function(g){
				g && g.update(pos);
			});
		};

		Helper.container.on("click",function(e){
			if( !game.isRuning )return;
			if(lock)return;
			lock = true;

			var pos = getPos(e);
			if(!pos)return;

			var a = pos.left - o.left;
			var b =  pos.top - o.top ;
			var c = Math.pow( a , 2) + Math.pow( b , 2 );
			var d = 0;

			c = Math.pow(c,0.5);

			if( b == 0 ){
				d = 90;
			}else{
				d = Math.abs( Math.atan( a / b ) ) ;
			}

			if( a < 0 ){
				d *= -1;
			}

			var gethandPos = function(c){
				return {
						left:o.left + c * Math.sin(d) - GOODS_OFFSET,
						top:o.top - c * Math.cos(d) - GOODS_OFFSET
					};
			};

			var robGoods = [];

			$hand.css({
				transform : "rotate("+( d * 180 / Math.PI )+"deg)"
			}).animate({height:c},{
				step:function(c){
					var p = gethandPos(c);
					robGoods = robGoods.concat(game.rob(p));
					updateRobGoods(robGoods, p);
				},complete:function(){
					$hand.animate({height:100},
						{
							speed:"fast" ,
							step:function(c){
								updateRobGoods(robGoods, gethandPos(c));
							},
							complete:function(){
								$.each(robGoods,function(i,g){
									g && g.$html.remove();
								});
								lock = false;
						}
					});	
				}
			});

		});

		setInterval((function(){
			var height = $hand.height();
			return function(){
				if( Math.abs(height - $hand.height()) < 0.001 )lock = false;
				height = $hand.height();
			}
		})(),1000);

		//html
		(function(){
			var show = function(selector){
				$(".overlayer, .overlayer " + selector).removeClass("fn-hide").show();
			};
			var hide = function(){
				$(".overlayer,.overlayer > div").addClass('fn-hide').hide();
			};

			$(document).on("click",".icon_gameDes",function(){
				//show(".login");
				game.pause();
			}).on("click",".overlayer_close,.btn_goOn",function(){
				hide();
				game.resume();
			}).on("click",".restart",function(){
				location.reload(); 
			});

			game.on("boom",function(g){
				g.type.score < 0 && show(".boom");
			}).on("end",function(){
				var isBoom = false , score;
				$.each(game.robGoods,function(i,g){
					if( g.type.score < 0){
						isBoom = true;
					}
				});
				if( isBoom )return;
				show('.success');
				$(".success .num").html( game.totalScore );
			}).on("start",function(){
				hide();
			}).on("boom",function(){
				var countToRestart = function(){};
				var count = 30;
				var $box = $(".boom");
				setInterval(function(){
					count--;
					count >= 0 && $box.find("span").html(count);
					if(!count)$box.find(".restart").removeClass("fn-hide");
				},1000);
			});
		})();

		game.start();
		game.onRob(function(goods){
			// 抓到物品
			if( goods.type.score < 0 ){
				game.trigger("boom",goods);
				game.stop();
				$hand.stop();
				return;
			}

			$("#gameTime").html(game.totalScore);

		}).onEnd(function(){
			//游戏结束
			//alert("end");
			$.each(game.goods,function(i,g){
				g && g.$html.remove();
			});

			game.goods = [];
		}).onCountDown(function(times){
			//倒数
			$(".progressNow").css("width", (100*times/TOTAL_TIME).toFixed() + "%" );
		}).onStart(function(){
			$("#gameTime").html(0);
			$(".progressNow").css("width","100%");
		});

	};

	$(function(){
		Helper.container.height($(window).height()-100);
		countToStart(STSRT_COUNTDOWN)
	});

	true && (function(){
		win.Helper = Helper;
		win.Game = Game;
		win.Goods = Goods;
	})();

})(window,window.jQuery)


//window.onerror = function(e){alert(e)}
